// 轮询管理器
/**
 * 定时轮询(可携带参数)
 * @param callback 回调方法
 * @param interval  轮询间隔时间
 * @returns
 */
export function createPollingInstance(callback: any, interval = 2000) {
  let timer: any;
  let isStop = false;

  const stop = () => {
    console.log("停止");
    isStop = true;
    clearTimeout(timer);
  };

  const start = async (valueToPass = {}) => {
    isStop = false;
    await loop(valueToPass);
  };

  const loop = async (valueToPass: any) => {
    try {
      await callback(stop, valueToPass);
    } catch (err: any) {
      console.error("轮询出错：", err);
      throw new Error("轮询出错：", err);
    }
    if (isStop) return;
    timer = setTimeout(loop, interval, valueToPass);
  };

  return {
    start,
    stop,
  };
}

// 轮询管理器
export function createPollingManager() {
  const instances: any[] = [];

  const addPollingInstance = (callback: any, interval: any, valueToPass: any) => {
    const instance = createPollingInstance(callback, interval);
    instances.push(instance);
    instance.start(valueToPass);
  };

  const removePollingInstance = (callback: any) => {
    const index = instances.findIndex(
      (instance) => instance.callback === callback
    );
    if (index !== -1) {
      instances[index].stop();
      instances.splice(index, 1);
    }
  };

  return {
    addPollingInstance,
    removePollingInstance,
  };
}
